const Router = require('koa-router');
const router = new Router();
const jwt = require("jsonwebtoken");
const myKey = "77bbFutureFloweMore";
var svgCaptcha = require('svg-captcha');
const path = require('path');
const formidable = require('formidable');
const Cookie = require('js-cookie')
router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})

router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

//张保
//注册
router.post('/api/register', async ctx => {
  const { userName, password } = ctx.request.body
  if (!userName || !password) {
    ctx.body = {
      success: false,
      message: '请输入用户名和密码'
    }
    return
  }
  const sql = `insert into user (userName, password) values ('${userName}', '${password}')`
  const R77 = ctx.request.body;
  const fw = await ctx.db.EXCUTE(sql, [R77.userName, R77.password])
  console.log(fw);
  ctx.body = { success: true };
})

router.get("/captcha", async (ctx, next) => {
  var captcha = svgCaptcha.create();
  str = captcha.text;
  ctx.body = captcha.data;
  console.log(captcha.text)
})

//登录
router.post("/login", async (ctx, next) => {
  let data = ctx.request.body;//请求体
  let sql = "select * from user where userName=? and password=?";
  result = JSON.stringify(await ctx.db.EXCUTE(sql, [data.userName, data.pwd]))//获取数据sql语句
  if (result.length != "2") {
    console.log(data.captcha);//自己输入的验证码
    console.log(str);//实际验证码
    if (data.captcha == str) {//如果一致
      let token = jwt.sign({ userName: data.userName }, myKey);//令牌
      ctx.body = {
        token: token, 'code': 200, 'message': '登陆成功'
      }
    } else {
      ctx.body = {
        'code': 400, 'message': '验证码错误'
      }
    }
  } else {
    ctx.body = {
      'code': 401, 'message': '用户名或密码错误'
    }
  }
})

//router.post('/upload', async (ctx, next) => {
//  let token = ctx.req.headers.authorization;
//  let result = jwt.verify(token, myKey);
//  console.log(result, "111111");
//  const form = formidable({
//    multiples: true,
//    uploadDir: path.join(__dirname, "../imgs"),
//    keepExtensions: true,
//  });
//
//  form.parse(ctx.req, (err, fields, files) => {
//    if (err) {
//      console.log(err);
//      return;
//    }
//  });
//})
//王国栋
router.post('/deliver', async (ctx, next) => {
  //res.set('Access-Control-Allow-Origin',"*")
  console.log(ctx.request.body)
  let body = ctx.request.body;
  let type = body.radio;
  let address = body.Address;
  let newaddress = body.newaddress;
  let phone = body.phone;
  let address1 = body.address1;
  let newaddress1 = body.newaddress1;
  let phone1 = body.phone1;
  let textarea = body.textarea;
  let value = body.value;
  let runprice = body.money;
  let sql = "insert into adddeliver (type,address,newaddress,phone,address1,newaddress1,phone1,textarea,value,runprice) values(?,?,?,?,?,?,?,?,?,?)"
  let sql2 = "insert into `order` (type,beginAddress,endAddress,newAddress,runprice,isOrder) values(?,?,?,?,?,-1)"
  let res = await ctx.db.EXCUTE(sql, [type, address, newaddress, phone, address1, newaddress1, phone1, textarea, value,runprice]);
  let result = await ctx.db.EXCUTE(sql2,[type,address,address1,newaddress,runprice])
  ctx.body = res;
  ctx.body = result;
})

router.post('/queue', async (ctx, next) => {
  //res.set('Access-Control-Allow-Origin',"*")
  let body = ctx.request.body;
  console.log(body);
  let type = body.radio;
  let address = body.Address;
  let newaddress = body.newAddress;
  let phone = body.phone;
  let value = body.value;
  let textarea = body.date1;
  let value1 = body.date2;
  let runprice = body.money;
  //let img = body.tempUrl;
  //let runprice = body.runprice
  let sql = "insert into addqueue (type,address,newaddress,phone,value,textarea,value1,runprice) values (?,?,?,?,?,?,?,?)"
  let sql2 = "insert into `order` (type,beginAddress,endAddress,newAddress,runprice,isOrder) values(?,?,?,?,?,-1)"
  let result = await ctx.db.EXCUTE(sql, [type, address, newaddress, phone, value, textarea, value1,runprice]);
  let res = await ctx.db.EXCUTE(sql2, [type, address, , newaddress, runprice])
  ctx.body = result;
  ctx.body = res;
})

//何航邱
//BuyPage的请求处理
router.post('/buy', async (ctx, next) => {
  let body = ctx.request.body;
  let type = body.content;
  let address1 = body.address1;
  let address2 = body.address2;
  let address3 = body.address3;
  let address4 = body.address4;
  let tel = body.tel;
  let yq = body.yq;
  let price = body.price;
  let time = body.time;
  let weight = body.weight;
  let runprice = body.runprice;
  let speacial = body.speacial;
  //sql语句到时候修改即可
  const insertSql = 'INSERT INTO buy (type,address1,address2,address3,address4,tel,yq,price,time,weight,runprice,speacial) VALUES (?, ?,?,?,?,?,?,?,?,?,?,?)';
  await ctx.db.EXCUTE(insertSql, [type, address1, address2, address3, address4, tel, yq, price, time, weight, runprice, speacial]);
  let sql2 = "insert into `order` (type,beginAddress,endAddress,newAddress,runprice,isOrder) values(?,?,?,?,?,-1)"
  let res = await ctx.db.EXCUTE(sql2, [type, address3, address1, address4, runprice])
  ctx.body = res;
  //console.log(data)
})
//DarwPage的请求处理
router.post('/draw', async (ctx, next) => {
  let body = ctx.request.body;
  //const data = ctx.request.body;
  let type = body.content;
  let address1 = body.address1;
  let address2 = body.address2;
  let address3 = body.address3;
  let address4 = body.address4;
  let tel1 = body.tel1;
  let tel2 = body.tel2;
  let bzxx = body.bzxx;
  let price = body.price;
  let time = body.time;
  let weight = body.weight;
  let runprice = body.runprice;
  //sql语句到时候修改即可
  const insertSql = 'INSERT INTO draw (type, address1,address2,address3,address4,tel1,tel2,bzxx,price,time,weight,runprice) VALUES (?, ?,?,?,?,?,?,?,?,?,?,?)';
  await ctx.db.EXCUTE(insertSql, [type, address1, address2, address3, address4, tel1, tel2, bzxx, price, time, weight, runprice]);
  let sql2 = "insert into `order` (type,beginAddress,endAddress,newAddress,runprice,isOrder) values(?,?,?,?,?,-1)"
  let res = await ctx.db.EXCUTE(sql2, [type, address3, address1, address4, runprice])
  ctx.body = res;
  //console.log(data)
})

//马鸣宇
router.post('/getList', async (ctx, next) => {
  let currentPage = ctx.request.body.currentPage;
  let pageSize = ctx.request.body.pageSize;
  let startRow = (currentPage - 1) * pageSize;
  let sql = `select orderId, type, src from product where isOrder = -1` + ` limit ${startRow},${pageSize}`;
  console.log(result = await ctx.db.EXCUTE('select * from product where isOrder = -1'));
  let length = result.length
  let dataList = await ctx.db.EXCUTE(sql)
  console.log(dataList);
  ctx.body = {
    results: dataList,
    length:length
  }
})

router.post('/postOrder', async (ctx, next) => {
  //console.log(ctx.request.body);
  let sql = "update `order` set isOrder= 1  where OrderId = ?"
  let dataList = await ctx.db.EXCUTE(sql, [ctx.request.body.OrderId])
  console.log(dataList);
  ctx.body = {
    success: true
  }
})

router.post('/getMessage', async (ctx, next) => {
  let OrderId = ctx.request.body.OrderId;
  console.log(OrderId)
  let sql = "select * from `order` where OrderId = ?"
  //isOrder,type,beginAddress,endAddress,newAddress,runprice
  let dataList = await ctx.db.EXCUTE(sql, [OrderId])
  ctx.body = dataList
})

//谢鸿蒲
// 编辑

router.post("/subeditform", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let userName = ctx.request.body.userName;
  let telephoneNum = ctx.request.body.telephoneNum;
  let eMail = ctx.request.body.eMail;
  let site = ctx.request.body.site;
  let timer = ctx.request.body.timer;
  console.log(chapterId)
  // let sql = "update user set userName="

  var sql = "update user set userName='" + userName + "',phone='" + telephoneNum + "',mail='" + eMail + "',address='" + site + "',timer='" + timer + "' where chapterId=" + chapterId + "";
  let result = await ctx.db.EXCUTE(sql);
  if (result) {
    ctx.body = { code: 200, status: "success" };
  } else {
    ctx.body = '编辑失败'
  }

})

// 添加数据

router.post("/subform", async (ctx, next) => {
  let userName = ctx.request.body.userName;
  let tel = ctx.request.body.telephoneNum;
  let eMail = ctx.request.body.eMail;
  let site = ctx.request.body.site;
  let timer = ctx.request.body.timer;
  let dateObj = new Date(timer);

  timer = dateObj.getFullYear() + "-"
    + (dateObj.getMonth() + 1) + "-"
    + dateObj.getDate();
  let sql = "insert into user (userName,phone,mail,address,timer) VALUES('" + userName + "','" + tel + "','" + eMail + "','" + site + "','" + timer + "')"
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  if (result) {
   ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "添加失败"
  }
})

// 删除

router.post("/delchapter", async (ctx, next) => {
  let chapterId = ctx.request.body.chapterId;
  let sql = "delete from user where chapterId=" + chapterId
  let result = await ctx.db.EXCUTE(sql);
  if (result) {

    ctx.body = { "code": 200, "msg": "ok" };
  } else {
    ctx.body = "删除失败"
  }

})

// 获取

router.get("/getnum", async (ctx, next) => {
  let num = []
  // let u = Cookie.get('username')

  // console.log(u)
  let sql = "select * from user  ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)

  result.forEach(item => {
    num.push({
      userName: item.userName,
      phone: item.phone,
      mail: item.mail,
      address: item.address,
      timer: item.timer,
      chapterId: item.chapterId
    })
  })

  ctx.body = num;

})
// 查询

router.post("/select", async (ctx, next) => {
  let text = ctx.request.body.text
  let sql = "select  *  from user where userName Like '%" + text + "%'"
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})

// logistics1.vue

// 获取
router.get("/l1", async (ctx, next) => {
  let logNum = []
  let sql = "select * from buy ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      type: item.type,
      tel: item.tel,
      weight: item.weight,
      address1: item.address1,
      timer: item.time,
      runprice: item.runprice,
      address2: item.address2,
      chapterId: item.chapterId
    })
  })
  ctx.body = logNum;
})

router.post("/selectlog", async (ctx, next) => {

  // console.log(1)
  // console.log(ctx.request.body)
  // ctx.body="1"
  let text = ctx.request.body.text
  let sql = "select *  from logistics1 where userName Like '%" + text + "%'"
  let result = await ctx.db.EXCUTE(sql);
  console.log(result)
  ctx.body = result
})

//文本框提交
router.post("/selectlogs", async (ctx, next) => {
  //console.log(ctx.request.body)
  //ctx.body="1"
  console.log(ctx.request.body)
  let body = ctx.request.body;
  let textarea = body.textarea;
  let sql = "insert into advice (textarea) value(?)";
  let result = ctx.db.EXCUTE(sql, [textarea]);
  ctx.request.body = result;
})


// logistics2.vue

// 获取
router.get("/l2", async (ctx, next) => {
  let logNum = []
  let sql = "select * from draw ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      type: item.type,
      tel: item.tel1,
      weight: item.weight,
      address1: item.address1,
      timer: item.time,
      chapterId: item.chapterId,
      address2:item.address2,
      runprice:item.runprice
    })
  })
  ctx.body = logNum;
})

//文本框提交
router.post("/selectlogs", async (ctx, next) => {
  console.log(ctx.request.body)
  ctx.body = "1"
  console.log(ctx.request.body)
  let body = ctx.request.body;
  let textarea = body.textarea;
  let sql = "insert into advice (textarea) value(?)";
  let result = ctx.db.EXCUTE(sql, [textarea]);
  ctx.request.body = result;
})

// logistics3.vue

// 获取
router.get("/l3", async (ctx, next) => {
  let logNum = []
  let sql = "select * from adddeliver ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      type: item.type,
      tel: item.phone,
      weight: item.textarea,
      site: item.address,
      timer: item.value,
      chapterId: item.chapterId,
      address:item.address,
      address1:item.address1,
      runprice:item.runprice
    })
  })
  ctx.body = logNum;
})
// logistics4.vue

// 获取
router.get("/l4", async (ctx, next) => {
  let logNum = []
  let sql = "select * from addqueue ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      type: item.type,
      tel: item.phone,
      weight: item.weight,
      site: item.address,
      timer: item.money,
      chapterId: item.chapterId,
      newaddress:item.newaddress,
      address:item.address,
      runprice:item.runprice
    })
  })
  ctx.body = logNum;
})

router.get("/l5", async (ctx, next) => {
  let logNum = []
  let sql = "select * from `order` where isOrder=1 ";
  let result = await ctx.db.EXCUTE(sql);
  // console.log(result)
  result.forEach(item => {
    console.log(item.userName)
    logNum.push({
      type: item.type,
      //tel: item.phone,
      //weight: item.weight,
      //site: item.address,
      //timer: item.money,
      //chapterId: item.chapterId,
      endAddress:item.endAddress,
      beginAddress:item.beginAddress,
      runprice:item.runprice
    })
  })
  ctx.body = logNum;
})

//个人信息页对应请求
router.post('/info',async(ctx,next)=>{
  ctx.body={title: 'koa info'}
  const data = ctx.request.body;
  console.log(data)
  ctx.state.username=(data.name);
  //console.log(ctx.request.data)
  let userName = data.name;
  //Cookie.get('username');
  console.log(userName)
  let phone = data.phone;
  console.log(phone)
  let address = data.address1;
  console.log(address)
  let mail = data.email
  console.log(mail)
  let sql = "update user set phone= ?,address=?,mail=? where userName = ?"
  //"insert into user (userName,phone,address,mail) values (?,?,?,?)"
  let res = await ctx.db.EXCUTE(sql,[phone,address,mail,userName]);
  ctx.body = res;
  //if(!data.name){
    //let sql = "insert into user (userName
  //}
  //let sql = "insert into user (userName"
  //console.log(ctx.state.username)
  //需要使用sql语句如下,下面img请求也是同理
   /* INSERT INTO table_name (column1, column2, column3) VALUES(value1, value2, value3)
   ON DUPLICATE KEY UPDATE column1=new_value1, column2=new_value2, column3=new_value3; */
   /*其中，table_name 为表名，column1、column2、column3 为列名，value1、value2、value3 是要插入的值，new_value1、new_value2、new_value3 是要更新的值，
   在这个语句中，column1、column2、column3 为主键或具有唯一索引的列，当插入记录时，如果该行已经存在，则执行 UPDATE 子句更新该行，否则插入一条新记录。 */
   /*注意：如果指定 ON DUPLICATE KEY UPDATE 子句，则不能将该表的 PRIMARY KEY 约束与 UNIQUE 约束中 的任何一个的 AUTO_INCREMENT 键属性设置为 否。 */
})

router.post('/img', async (ctx, next) => {
  let updirPath = path.join(__dirname, '../uploads');
  
  let form = formidable({
    multiples: true,
    uploadDir: updirPath,
    keepExtensions: true
  })
  form.parse(ctx.req, async (err, fields, files) => {
    if (err) {
      console.log(err);
    }
    //let img = JSON.stringify(files);
    //let imgs = JSON.parse(img).file;
    //console.log(form)
    let filepath = files.avatar.filepath
    ctx.state.imgpath =filepath;
    let name = files.avatar.originalFilename
    console.log('图片路径:'+filepath,'图片名字:'+name)
   
  })
})
module.exports = router
